# -*- coding:utf-8 -*-
"""
@Time : 2020-12-15 11:54
@Author: langengel
@Des: 助手工具库
"""

import smtplib
from email.mime.text import MIMEText
import hashlib
from passlib.handlers.pbkdf2 import pbkdf2_sha256
from config.email import HOST, PWD, PORT, SENDER
import uuid
import time
import random
from saas.response.BaseResponse import success


def en_password(psw: str):
    """
    密码加密
    :param psw: 需要加密的密码
    :return: 加密后的密码
    """
    password = pbkdf2_sha256.hash(psw)
    return password


def check_password(password: str, old: str):
    """
    密码校验
    :param password: 用户输入的密码
    :param old: 数据库密码
    :return: Boolean
    """
    check = pbkdf2_sha256.verify(password, old)
    if check:
        return True
    else:
        return False


async def getcode():
    """
    获取web_code请求码
    :return:
    """
    return success(data={
        "web_code": req_code()
    })


def req_code():
    """
    唯一随机字符串
    :return: str
    """
    only = hashlib.md5(str(uuid.uuid1()).encode(encoding='UTF-8')).hexdigest()
    return str(only)


def get_times():
    """
    当前毫秒时间戳
    :return: 时间戳13位
    """
    return int(round(time.time() * 1000))



def get_time_string():
    """
    当前时间转字符串格式
    :return: 2009-01-01 00:00:00
    """
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))


def code_number(ln: int):
    """
    随机数字
    :param ln: 长度
    :return: int
    """
    code = ""
    for i in range(ln):
        ch = chr(random.randrange(ord('0'), ord('9') + 1))
        code += ch

    return code


def zfill(first: str, number: int, length: int):
    """
    数字前置左侧补零  业务id
    :param first: 前置字符串
    :param number: 真实数字
    :param length: 长度
    :return:
    """
    return str(first + str(number).zfill(length))


def send_email(receiver: str, html: str, title: str):
    # 第三方 SMTP 服务

    host = HOST
    # 设置发件服务器地址
    port = PORT
    # 设置发件服务器端口号。注意，这里有SSL和非SSL两种形式，现在一般是SSL方式
    sender = SENDER
    # 设置发件邮箱，一定要自己注册的邮箱
    pwd = PWD
    # 设置发件邮箱的授权码密码，根据163邮箱提示，登录第三方邮件客户端需要授权码
    print(receiver)
    receiver = receiver
    # 设置邮件接收人，可以是QQ邮箱
    body = html
    # 设置邮件正文，这里是支持HTML的
    msg = MIMEText(body, 'html')
    # 设置正文为符合邮件格式的HTML内容
    msg['subject'] = title
    # 设置邮件标题
    msg['from'] = sender
    # 设置发送人
    msg['to'] = receiver
    # 设置接收人
    try:
        s = smtplib.SMTP_SSL(host, port)
        # 注意！如果是使用SSL端口，这里就要改为SMTP_SSL
        s.login(sender, pwd)
        # 登陆邮箱
        s.sendmail(sender, receiver, msg.as_string())
        # 发送邮件！
        return True
    except smtplib.SMTPException:
        return False
